#!/usr/bin/env python
# coding=utf-8
from bencoder import bencode,bdecode
import base64

import time

import os

num=0
# file_path = os.getcwd() #获取当前工作环境路径
def go_torrents(file_names,full_metadata):
    """
    接收mongol里面的file_data,并解码,生成种子文字文件
    :param file_names:
    :param full_metadata:
    :return:
    """
    full_metadata = bdecode(base64.b64decode(full_metadata.encode()))   #接收mongol里面的file_data,并解码
    file_path=os.path.dirname(os.path.realpath(__file__))
    os.chdir(file_path + "/" + "file_cache")   #工作路径
    if len(file_names) >20:
        file_name =file_names[0:20]
    else:
        file_name=file_names
    filename = '{}.torrent'.format(file_name)   #文件名
    torrent = {
        'nodes': [],
        'info': full_metadata
    }
    with open(filename, 'wb') as f:         #创建文件
        # print("__****__{}".format(bencode(torrent)))
        seed =bencode(torrent)
        f.write(seed)
    f.close()
    return filename


def dht_analysis (torrent):
    """
    解析文件信息
    :param torrent:
    :return:
    """

    fileslist={}
    data = torrent
    try:
        allfiles =data[b'name'].decode("utf-8",)
        times = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        try:            #判断一下，有的种子只有一个文件，不存在files这个属性
            for i in range(len(data[b'files'])):
                        # print("___{}___".format(i))
                files = data[b'files'][i]           #文件
                length = bytes(files[b"length"])       #长度
                path = files[b'path'][0].decode()   #.html链接
                        #print(data[b'files'][i])
                        #print(data[b'files'][i][b"length"])
                        #print(data[b'files'][i][b'path'][0].decode())
                        # 格式化成2016-03-20 11:45:39形式
                        #print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                fileslist.update({"{}".format(i):[length,path]})
        except KeyError:        #KeyError: b'files'

            try:
                length = bytes(data[b"length"] ) # 长度
                path = data[b'path'].decode()  # .html链接
                print(path)
                fileslist.update({"0": [length, path]})
            except KeyError:     #KeyError: b'path'
                length = bytes(data[b"length"])
                fileslist.update({"0": [length, allfiles]})
        except TimeoutError:
            pass
        return allfiles, times, fileslist
    except UnicodeDecodeError:
        print("编码方式不同已经跳过")
        pass


def bytes(bytes):
    """
    转化文件大小显示
    :param bytes:
    :return:
    """

    if bytes < 1024:  #比特
        bytes = str(round(bytes, 2)) + ' B' #字节
    elif bytes >= 1024 and bytes < 1024 * 1024:
        bytes = str(round(bytes / 1024, 2)) + ' KB' #千字节
    elif bytes >= 1024 * 1024 and bytes < 1024 * 1024 * 1024:
        bytes = str(round(bytes / 1024 / 1024, 2)) + ' MB' #兆字节
    elif bytes >= 1024 * 1024 * 1024 and bytes < 1024 * 1024 * 1024 * 1024:
        bytes = str(round(bytes / 1024 / 1024 / 1024, 2)) + ' GB' #千兆字节
    elif bytes >= 1024 * 1024 * 1024 * 1024 and bytes < 1024 * 1024 * 1024 * 1024 * 1024:
        bytes = str(round(bytes / 1024 / 1024 / 1024 / 1024, 2)) + ' TB' #太字节
    elif bytes >= 1024 * 1024 * 1024 * 1024 * 1024 and bytes < 1024 * 1024 * 1024 * 1024 * 1024 * 1024:
        bytes = str(round(bytes / 1024 / 1024 / 1024 / 1024 / 1024, 2)) + ' PB' #拍字节
    elif bytes >= 1024 * 1024 * 1024 * 1024 * 1024 * 1024 and bytes < 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024:
        bytes = str(round(bytes / 1024 / 1024 / 1024 / 1024 / 1024 /1024, 2)) + ' EB' #艾字节
    return bytes
# async def test_example(loop):
#     global num
#       #实例化Maga
#     pool = await aiomysql.connect(host='localhost', port=3306,user='dht_text', password='zxcasd',db='dht_cache', loop=loop)
#
#     # create default cursor 创建分离游标
#     # cursor = await pool.cursor()
#
#     # execute sql query执行sql查询
#     # await cursor.execute("select * from dht_cache")
#
#     # fetch all results 获取所有的结果
#     while True:
#         # 直接存储metainfo
#         info_hash, data = await Maga().data_q.get()
#         data_q_len = Maga().data_q.qsize()
#         print('队列的目前长度{}'.format(data_q_len))
#         print('data_q-->get')
#         # fetch_result = await cursor.fetchall()
#         num += 1
#         res = base64.b64decode(data.encode())
#         print("_________{}____________".format(num))
#         # print(res)
#         file_name = (res[b'name'].decode())
#         reed = to_torrent(file_name,res)   #生成种子文件
#         print("********************************")
#         # print(reed)
#         msg = dht_analysis(res)
#         a, b, c = msg
#         print( a,b,c,reed)
#         async with pool.acquire() as conn:
#             async with conn.cursor() as cur:
#                 try:
#                     # await cur.execute("insert into dht_cache (info_hash,value) values('{}','{}');".format(info_hash, data))
#                     await cur.close()
#                     await conn.commit()
#                 except Exception as e:
#                     print('insert err{}'.format(e))


    # # detach cursor from connectiond 关闭分离游标
    # await cursor.close()
    #
    # # close connection关闭连接
    # pool.close()


# if __name__=="__main__":
#     loop = asyncio.get_event_loop()
#     loop.run_until_complete(test_example())
